﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Criterion;

namespace SafeNet.InitialDatabase.Repository
{
    public class NHibernateRepositoryBase<T> : IRepository<T>  
    {

        protected readonly ISessionBuilder m_SessionBuilder;

        private ISession m_Session;
        private ITransaction m_Transaction;

        public NHibernateRepositoryBase()
        {
            m_SessionBuilder = SessionBuilderFactory.CurrentBuilder;
        }

        public NHibernateRepositoryBase(ISession session, ITransaction transaction)
        {
            m_Session = session;
            m_Transaction = transaction;
        }

        protected virtual ISession GetSession()
        {
            if (m_Session == null)
            {
                return m_SessionBuilder.CurrentSession;
            }
            else
            {
                return m_Session;
            }
        }

        public T FindById(object key)
        {
            return GetSession().Load<T>(key);
        }

        public IList<T> FindAll()
        {
            return GetSession().CreateCriteria(typeof(T)).List<T>();
        }

        public void Save(T item)
        {
            GetSession().Save(item);
        }

        public void Delete(T item)
        {
            GetSession().Delete(item);
        }
    }

}
